#!/bin/bash
# =================================================================
# LimeReader macOS 一键部署脚本
# 功能：构建 -> 打包DMG -> 生成version.json -> 准备OSS上传
# =================================================================

set -e  # 遇到错误立即退出

# 项目配置
CLIENT_DIR="limereader"
PROJECT_VERSION="2.7.2"
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
DEPLOY_DIR="${SCRIPT_DIR}/../deploy"
UPLOAD_DIR="${DEPLOY_DIR}/uploads/${CLIENT_DIR}"
BUILD_DIR="${SCRIPT_DIR}/build_release"
DIST_DIR="${SCRIPT_DIR}/dist"

# OSS配置
OSS_BUCKET="limereader-releases"
OSS_BASE_URL="https://limereader-releases.oss-cn-hangzhou.aliyuncs.com"
OSS_PREFIX="updates/${CLIENT_DIR}"

# 参数解析
CLEAN_BUILD=false
SKIP_BUILD=false
AUTO_UPLOAD=false

show_help() {
    echo ""
    echo "========================================"
    echo " LimeReader macOS 一键部署脚本"
    echo "========================================"
    echo ""
    echo "用法: ./onekey_mac_deploy.sh [选项]"
    echo ""
    echo "选项:"
    echo "  -v, --version VERSION     指定版本号（默认: 2.7.2）"
    echo "  -c, --clean               构建前清理"
    echo "  -s, --skip-build          跳过构建，仅打包"
    echo "  -u, --upload              构建完成后上传到OSS"
    echo "  -h, --help                显示帮助"
    echo ""
    echo "示例:"
    echo "  ./onekey_mac_deploy.sh                 # 完整构建和打包"
    echo "  ./onekey_mac_deploy.sh -c              # 清理后重新构建"
    echo "  ./onekey_mac_deploy.sh -v 2.7.3        # 指定版本号"
    echo "  ./onekey_mac_deploy.sh -u              # 构建并上传到OSS"
    echo "  ./onekey_mac_deploy.sh -s -u           # 跳过构建，仅打包并上传"
    echo ""
    exit 0
}

# 解析命令行参数
while [[ $# -gt 0 ]]; do
    case $1 in
        -v|--version)
            PROJECT_VERSION="$2"
            shift 2
            ;;
        -c|--clean)
            CLEAN_BUILD=true
            shift
            ;;
        -s|--skip-build)
            SKIP_BUILD=true
            shift
            ;;
        -u|--upload)
            AUTO_UPLOAD=true
            shift
            ;;
        -h|--help)
            show_help
            ;;
        *)
            echo "未知参数: $1"
            show_help
            ;;
    esac
done

echo ""
echo "========================================"
echo " LimeReader macOS 一键部署脚本"
echo " 版本: ${PROJECT_VERSION}"
echo "========================================"
echo ""

# 检查必要工具
echo "[INFO] 检查构建工具..."

if ! command -v cmake &> /dev/null; then
    echo "[ERROR] 未找到 CMake，请安装："
    echo "  brew install cmake"
    exit 1
fi

if ! command -v qmake &> /dev/null; then
    echo "[ERROR] 未找到 Qt，请安装："
    echo "  brew install qt@6"
    echo "  并添加到 PATH: export PATH=\"/opt/homebrew/opt/qt@6/bin:\$PATH\""
    exit 1
fi

if ! command -v macdeployqt &> /dev/null; then
    echo "[ERROR] 未找到 macdeployqt，请确保 Qt bin 目录在 PATH 中"
    echo "  export PATH=\"/opt/homebrew/opt/qt@6/bin:\$PATH\""
    exit 1
fi

# create-dmg
if ! command -v create-dmg &> /dev/null; then
    echo "[ERROR] 未找到 create-dmg，请安装："
    echo "  brew install create-dmg"
    exit 1
fi

echo "[SUCCESS] 构建工具检查通过"

# 检查Poppler库
if brew list poppler &> /dev/null; then
    echo "[SUCCESS] 找到 Poppler 库，PDF 功能可用"
else
    echo "[WARNING] 未找到 Poppler 库，建议安装："
    echo "  brew install poppler"
fi

# 清理旧文件
if [ "$CLEAN_BUILD" = true ]; then
    echo ""
    echo "[INFO] 清理旧的构建文件..."
    rm -rf "$BUILD_DIR"
    rm -rf "$DIST_DIR"
    rm -rf "$UPLOAD_DIR"
    echo "[SUCCESS] 清理完成"
elif [ "$SKIP_BUILD" = false ]; then
    echo ""
    echo "[INFO] 清理上传目录..."
    rm -rf "$UPLOAD_DIR"
fi

# 构建应用程序
if [ "$SKIP_BUILD" = false ]; then
    echo ""
    echo "[INFO] 开始构建应用程序..."
    
    # 创建构建目录
    echo "[INFO] 创建构建目录..."
    mkdir -p "$BUILD_DIR"
    cd "$BUILD_DIR"
    
    echo ""
    echo "[INFO] 配置项目 (CMake)..."
    cmake -DCMAKE_BUILD_TYPE=Release \
          -DPROJECT_VERSION_OVERRIDE="${PROJECT_VERSION}" \
          ..
    
    if [ $? -ne 0 ]; then
        echo "[ERROR] CMake 配置失败"
        exit 1
    fi
    
    echo ""
    echo "[INFO] 编译应用 (make)..."
    make -j$(sysctl -n hw.ncpu)
    
    if [ $? -ne 0 ]; then
        echo "[ERROR] 编译失败"
        exit 1
    fi
    
    echo "[SUCCESS] 应用编译完成"
else
    echo ""
    echo "[INFO] 跳过构建，使用现有构建结果..."
    
    # 检查构建产物是否存在
    if [ ! -f "$BUILD_DIR/bin/Release/LimeReader.app/Contents/MacOS/LimeReader" ]; then
        echo "[ERROR] 找不到已构建的程序"
        echo "        请先运行完整构建或移除 -s 参数"
        exit 1
    fi
    echo "[SUCCESS] 找到已构建的程序"
fi

# 创建发布目录
echo ""
echo "[INFO] 准备发布文件..."
mkdir -p "$DIST_DIR"

# 复制.app到发布目录
APP_PATH="$BUILD_DIR/bin/Release/LimeReader.app"
DIST_APP_PATH="$DIST_DIR/LimeReader.app"

if [ ! -d "$APP_PATH" ]; then
    echo "[ERROR] 未找到 .app 文件: $APP_PATH"
    exit 1
fi

echo "[INFO] 复制应用程序包..."
rm -rf "$DIST_APP_PATH"
cp -R "$APP_PATH" "$DIST_APP_PATH"

# 部署Qt依赖
echo ""
echo "[INFO] 部署Qt依赖库..."
macdeployqt "$DIST_APP_PATH" -verbose=2

if [ $? -ne 0 ]; then
    echo "[WARNING] macdeployqt 执行有警告"
fi

# 手动复制 QtDBus（macdeployqt 可能遗漏）
echo ""
echo "[INFO] 检查并复制 QtDBus 框架..."
QT_FRAMEWORKS_DIR="$DIST_APP_PATH/Contents/Frameworks"
if [ ! -d "$QT_FRAMEWORKS_DIR/QtDBus.framework" ]; then
    # 查找 QtDBus
    QTDBUS_PATH=$(find /opt/homebrew/Cellar/qt -name "QtDBus.framework" -type d 2>/dev/null | head -1)
    if [ -z "$QTDBUS_PATH" ]; then
        QTDBUS_PATH="/opt/homebrew/opt/qt/lib/QtDBus.framework"
    fi
    
    if [ -d "$QTDBUS_PATH" ]; then
        echo "[INFO] 复制 QtDBus.framework 从 $QTDBUS_PATH"
        cp -R "$QTDBUS_PATH" "$QT_FRAMEWORKS_DIR/"
        
        # 修复 QtDBus 的依赖路径
        QTDBUS_BIN="$QT_FRAMEWORKS_DIR/QtDBus.framework/Versions/A/QtDBus"
        if [ -f "$QTDBUS_BIN" ]; then
            install_name_tool -id "@rpath/QtDBus.framework/Versions/A/QtDBus" "$QTDBUS_BIN" 2>/dev/null || true
            # 修复其依赖的其他 Qt 框架路径
            for dep in QtCore; do
                install_name_tool -change "@rpath/$dep.framework/Versions/A/$dep" "@rpath/$dep.framework/Versions/A/$dep" "$QTDBUS_BIN" 2>/dev/null || true
            done
        fi
        echo "[SUCCESS] QtDBus 已复制"
    else
        echo "[WARNING] 未找到 QtDBus.framework"
    fi
else
    echo "[INFO] QtDBus.framework 已存在"
fi

# 手动复制 Poppler 依赖库（macdeployqt 可能遗漏）
echo ""
echo "[INFO] 复制 Poppler 依赖库..."
FRAMEWORKS_DIR="$DIST_APP_PATH/Contents/Frameworks"

# 检查是否已有 libpoppler-cpp
if [ -f "$FRAMEWORKS_DIR/libpoppler-cpp.2.dylib" ]; then
    echo "[INFO] 检测到 libpoppler-cpp.2.dylib，查找其依赖..."
    
    # 从 Homebrew 复制完整的 poppler 库
    if [ -d "/opt/homebrew/Cellar/poppler" ]; then
        POPPLER_DIR=$(find /opt/homebrew/Cellar/poppler -type d -name "lib" | head -1)
        
        if [ -n "$POPPLER_DIR" ]; then
            echo "[INFO] 从 $POPPLER_DIR 复制 poppler 库..."
            
            # 复制所有 poppler 相关的 dylib
            for lib in "$POPPLER_DIR"/libpoppler*.dylib; do
                if [ -f "$lib" ]; then
                    LIB_NAME=$(basename "$lib")
                    if [ ! -f "$FRAMEWORKS_DIR/$LIB_NAME" ]; then
                        echo "  复制: $LIB_NAME"
                        cp "$lib" "$FRAMEWORKS_DIR/"
                    fi
                fi
            done
            
            # 修复所有 poppler 库的路径
            for lib in "$FRAMEWORKS_DIR"/libpoppler*.dylib; do
                if [ -f "$lib" ]; then
                    LIB_NAME=$(basename "$lib")
                    
                    # 修改 install name
                    install_name_tool -id "@rpath/$LIB_NAME" "$lib" 2>/dev/null || true
                    
                    # 修复内部依赖
                    otool -L "$lib" | grep "libpoppler" | awk '{print $1}' | while read dep; do
                        if [[ "$dep" == /opt/homebrew/* ]] || [[ "$dep" == @rpath/* ]]; then
                            DEP_NAME=$(basename "$dep")
                            install_name_tool -change "$dep" "@rpath/$DEP_NAME" "$lib" 2>/dev/null || true
                        fi
                    done
                fi
            done
            
            echo "[SUCCESS] Poppler 库复制并修复完成"
        else
            echo "[WARNING] 未找到 Homebrew poppler 库目录"
        fi
    else
        echo "[WARNING] 未找到 Homebrew poppler 安装"
    fi
fi

# 修复主应用的 rpath（关键！在签名之前）
echo ""
echo "[INFO] 修复应用 rpath..."
MAIN_EXEC="$DIST_APP_PATH/Contents/MacOS/LimeReader"

# 添加 Frameworks 到 rpath（如果尚未添加）
if ! otool -l "$MAIN_EXEC" | grep -q "@executable_path/../Frameworks"; then
    echo "[INFO] 添加 @executable_path/../Frameworks 到 rpath"
    install_name_tool -add_rpath "@executable_path/../Frameworks" "$MAIN_EXEC" 2>/dev/null || true
    echo "[SUCCESS] rpath 已更新"
else
    echo "[INFO] rpath 已包含 Frameworks 路径"
fi

# 验证 rpath
echo "[INFO] 当前 rpath 配置:"
otool -l "$MAIN_EXEC" | grep -A 3 "LC_RPATH" | grep "path" || true

# Ad-hoc 代码签名（必须，否则macOS无法运行）
echo ""
echo "[INFO] 执行 ad-hoc 代码签名..."

# 1. 签名所有dylib和framework
echo "[INFO] 签名依赖库..."
find "$DIST_APP_PATH/Contents" -type f \( -name "*.dylib" -o -name "*.so" \) -exec codesign --force --sign - --timestamp=none {} \; 2>/dev/null || true

if [ -d "$DIST_APP_PATH/Contents/Frameworks" ]; then
    for fw in "$DIST_APP_PATH/Contents/Frameworks"/*.framework; do
        if [ -d "$fw" ]; then
            echo "  签名: $(basename $fw)"
            codesign --force --sign - --timestamp=none --deep "$fw" 2>/dev/null || true
        fi
    done
fi

# 2. 签名插件
if [ -d "$DIST_APP_PATH/Contents/PlugIns" ]; then
    echo "[INFO] 签名插件..."
    find "$DIST_APP_PATH/Contents/PlugIns" -type f -perm +111 -exec codesign --force --sign - --timestamp=none {} \; 2>/dev/null || true
fi

# 3. 最后签名主应用
echo "[INFO] 签名主应用..."

# 创建临时 entitlements 文件
TEMP_ENTITLEMENTS=$(mktemp /tmp/limereader_entitlements.XXXXXX)
cat > "$TEMP_ENTITLEMENTS" << 'EOF'
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>com.apple.security.cs.allow-jit</key>
    <true/>
    <key>com.apple.security.cs.allow-unsigned-executable-memory</key>
    <true/>
    <key>com.apple.security.cs.disable-library-validation</key>
    <true/>
</dict>
</plist>
EOF

# 使用临时文件进行签名
codesign --force --sign - --timestamp=none --deep --entitlements "$TEMP_ENTITLEMENTS" "$DIST_APP_PATH" 2>&1 || true

# 清理临时文件
rm -f "$TEMP_ENTITLEMENTS"

# 验证签名
echo "[INFO] 验证签名..."
if codesign -v "$DIST_APP_PATH" 2>&1; then
    echo "[SUCCESS] 代码签名完成并验证通过"
else
    echo "[WARNING] 代码签名验证失败，但继续执行"
fi

########################################
# 使用 create-dmg 创建精美DMG
echo ""
echo "[INFO] 创建DMG安装包 (create-dmg)..."

DMG_NAME="LimeReader_v${PROJECT_VERSION}_macOS.dmg"
DMG_TEMP="${DIST_DIR}/dmg_temp"
DMG_PATH="${DIST_DIR}/${DMG_NAME}"

# 清理
rm -rf "$DMG_TEMP" && mkdir -p "$DMG_TEMP"
rm -f "$DMG_PATH"

# 复制应用
cp -R "$DIST_APP_PATH" "$DMG_TEMP/"

# 写入指引文件
cat > "$DMG_TEMP/使用说明.txt" << 'EOF'
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
🎯 LimeReader - 长图处理
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

安装方法：将「LimeReader.app」拖拽到「Applications」文件夹
EOF

cat > "$DMG_TEMP/Gatekeeper_绕过指南.txt" << 'EOF'
🛡️ Gatekeeper 绕过指南（首次被阻止时）
1) 在「应用程序」中右键 LimeReader.app → 打开 → 再点“打开”
2) 系统设置 → 隐私与安全性 → 允许来自开发者的应用
3) 或在终端执行：xattr -dr com.apple.quarantine /Applications/LimeReader.app
EOF

# 背景与卷标图标
SCRIPT_DIR_ABS="${SCRIPT_DIR}"
DMG_RES_DIR="${SCRIPT_DIR_ABS}/dmg"
BG_PNG="${DMG_RES_DIR}/background.png"
VOL_ICNS="${DMG_RES_DIR}/volume.icns"

# 预处理背景到临时目录
BG_ARGS=()
WINDOW_W=800
WINDOW_H=600
if [ -f "$BG_PNG" ]; then
  mkdir -p "$DMG_TEMP/.background"
  SAN_BG="$DMG_TEMP/.background/background.png"
  cp -f "$BG_PNG" "$SAN_BG" || true
  if command -v sips &>/dev/null; then
    sips -s format png "$SAN_BG" --out "$SAN_BG" >/dev/null 2>&1 || true
    sips -s dpiWidth 72 -s dpiHeight 72 "$SAN_BG" >/dev/null 2>&1 || true
    sips -z $WINDOW_H $WINDOW_W "$SAN_BG" >/dev/null 2>&1 || true
  fi
  BG_ARGS=(--background "$SAN_BG")
else
  echo "[WARNING] 未找到DMG背景图: $BG_PNG"
fi

VOL_ARGS=()
if [ -f "$VOL_ICNS" ]; then
  VOL_ARGS=(--volicon "$VOL_ICNS")
fi

# 计算布局（菱形 + 顶部两文档）
CX=$((WINDOW_W/2))
CY=$((WINDOW_H/2))
OFFSET_X=240
OFFSET_Y=200
APP_X=$((CX - OFFSET_X))
APP_Y=$((CY))
APPS_X=$((CX + OFFSET_X))
APPS_Y=$((CY))
TOP_Y=$((CY - OFFSET_Y))
# 文本图标内侧距中心线40px → 中心偏移=104
TXT_SPACING=104
TOP_LEFT_X=$((CX - TXT_SPACING))
TOP_RIGHT_X=$((CX + TXT_SPACING))

echo "[INFO] 生成DMG (create-dmg)..."
if create-dmg \
  --volname "LimeReader" \
  "${VOL_ARGS[@]}" \
  "${BG_ARGS[@]}" \
  --window-pos 200 120 \
  --window-size $WINDOW_W $WINDOW_H \
  --icon-size 128 \
  --icon "LimeReader.app" $APP_X $APP_Y \
  --app-drop-link $APPS_X $APPS_Y \
  --icon "使用说明.txt" $TOP_LEFT_X $TOP_Y \
  --icon "Gatekeeper_绕过指南.txt" $TOP_RIGHT_X $TOP_Y \
  "$DMG_PATH" \
  "$DMG_TEMP"; then
  echo "[SUCCESS] DMG创建成功: ${DMG_NAME}"
else
  echo "[WARNING] 带背景创建失败，尝试无背景..."
  rm -f "$DMG_PATH"
  if ! create-dmg \
    --volname "LimeReader" \
    "${VOL_ARGS[@]}" \
    --window-pos 200 120 \
    --window-size $WINDOW_W $WINDOW_H \
    --icon-size 128 \
    --icon "LimeReader.app" $APP_X $APP_Y \
    --app-drop-link $APPS_X $APPS_Y \
    --icon "使用说明.txt" $TOP_LEFT_X $TOP_Y \
    --icon "Gatekeeper_绕过指南.txt" $TOP_RIGHT_X $TOP_Y \
    "$DMG_PATH" \
    "$DMG_TEMP"; then
      echo "[ERROR] DMG创建失败"
      exit 1
  fi
fi

# 清理临时目录
rm -rf "$DMG_TEMP"

# 创建上传目录
echo ""
echo "[INFO] 创建上传目录..."
mkdir -p "$UPLOAD_DIR"

# 复制DMG到上传目录
echo "[INFO] 复制DMG到上传目录..."
cp "$DMG_PATH" "$UPLOAD_DIR/"

# 计算文件信息
echo ""
echo "[INFO] 计算文件信息..."

DMG_UPLOAD_PATH="${UPLOAD_DIR}/${DMG_NAME}"
DMG_SIZE_BYTES=$(stat -f%z "$DMG_UPLOAD_PATH")
DMG_SIZE_MB=$(echo "scale=2; $DMG_SIZE_BYTES / 1024 / 1024" | bc)
DMG_HASH=$(md5 -q "$DMG_UPLOAD_PATH")

echo "[INFO] DMG大小: ${DMG_SIZE_MB} MB"
echo "[INFO] DMG MD5: ${DMG_HASH}"

########################################
# 生成/合并 version.json（先拉远端再合并）
echo ""
echo "[INFO] 生成version.json..."

VERSION_JSON_PATH="${UPLOAD_DIR}/version.json"
RELEASE_DATE=$(date -u +"%Y-%m-%dT%H:%M:%SZ")
REMOTE_TMP="${UPLOAD_DIR}/version.remote.json"

echo "[INFO] 尝试从OSS读取现有 version.json 用于合并..."
if curl -fsS "${OSS_BASE_URL}/${OSS_PREFIX}/version.json" -o "$REMOTE_TMP" 2>/dev/null; then
  if python3 - "$REMOTE_TMP" << 'PY'
import json,sys
try:
    json.load(open(sys.argv[1], 'r', encoding='utf-8'))
    sys.exit(0)
except Exception:
    sys.exit(1)
PY
  then
    mv -f "$REMOTE_TMP" "$VERSION_JSON_PATH"
    echo "[SUCCESS] 已获取远端版本作为合并基准"
  else
    echo "[WARNING] 远端version.json格式无效，忽略"
    rm -f "$REMOTE_TMP"
  fi
else
  echo "[INFO] 远端暂无version.json，将创建新的"
fi

# 导出环境变量供Python使用
export VERSION_JSON_PATH
export PROJECT_VERSION
export RELEASE_DATE
export OSS_BASE_URL
export OSS_PREFIX
export DMG_NAME
export DMG_SIZE_MB
export DMG_HASH

python3 - << PY
import json, os, sys
path = os.environ['VERSION_JSON_PATH']
project_version = os.environ['PROJECT_VERSION']
release_date = os.environ['RELEASE_DATE']
oss_base = os.environ['OSS_BASE_URL']
oss_prefix = os.environ['OSS_PREFIX']
dmg_name = os.environ['DMG_NAME']
dmg_size = os.environ['DMG_SIZE_MB'] + ' MB'
dmg_hash = os.environ['DMG_HASH']

data = {}
if os.path.exists(path):
    try:
        with open(path, 'r', encoding='utf-8') as f:
            data = json.load(f)
    except Exception:
        data = {}

data['latestVersion'] = project_version
data['releaseDate'] = release_date
data['releaseNotes'] = f"LimeReader 版本 {project_version}\\n- 性能优化\\n- Bug修复\\n- 功能改进"
data['forceUpdate'] = False

packages = data.get('packages') or {}
packages['macos'] = {
    'url': dmg_name,
    'size': dmg_size,
    'hash': dmg_hash,
    'downloadUrl': f"{oss_base}/{oss_prefix}/{dmg_name}",
    'description': 'macOS 磁盘镜像',
    'minSystemVersion': 'macOS 10.15 或更高版本'
}
data['packages'] = packages

with open(path, 'w', encoding='utf-8') as f:
    json.dump(data, f, indent=2, ensure_ascii=False)
print('version.json 已合并/创建')
PY

echo "[SUCCESS] version.json 已更新（合并远端+macOS段）"

# 生成OSS上传脚本
echo ""
echo "[INFO] 生成OSS上传脚本..."

UPLOAD_SCRIPT_PATH="${UPLOAD_DIR}/upload_to_oss.sh"

cat > "$UPLOAD_SCRIPT_PATH" << 'UPLOAD_SCRIPT_EOF'
#!/bin/bash
# OSS上传脚本 - 自动生成

set -e

CLIENT_DIR="limereader"
VERSION="PROJECT_VERSION_PLACEHOLDER"
BUCKET="limereader-releases"
ENDPOINT="oss-cn-hangzhou.aliyuncs.com"
OSS_PREFIX="updates/${CLIENT_DIR}"
UPLOAD_DIR="$(cd "$(dirname "$0")" && pwd)"
DEPLOY_DIR="${UPLOAD_DIR}/../.."

echo "开始上传 LimeReader v${VERSION} 到阿里云OSS..."
echo ""

# 加载OSS配置（如果存在）
if [ -f "${DEPLOY_DIR}/oss-config.sh" ]; then
    echo "✓ 加载OSS配置: ${DEPLOY_DIR}/oss-config.sh"
    source "${DEPLOY_DIR}/oss-config.sh"
fi

# 检查ossutil
if ! command -v ossutil &> /dev/null; then
    echo "❌ 错误: 未找到ossutil"
    echo "安装方法:"
    echo "  下载地址: https://help.aliyun.com/zh/oss/developer-tools/ossutil"
    exit 1
fi

# 验证ossutil版本
OSSUTIL_VERSION=$(ossutil version 2>&1 || echo "unknown")
echo "✓ ossutil 版本: ${OSSUTIL_VERSION}"

# 构建认证参数
AUTH_PARAMS=""
if [ -n "$OSS_ACCESS_KEY_ID" ] && [ -n "$OSS_ACCESS_KEY_SECRET" ]; then
    echo "✓ 使用环境变量中的OSS密钥"
    AUTH_PARAMS="--access-key-id ${OSS_ACCESS_KEY_ID} --access-key-secret ${OSS_ACCESS_KEY_SECRET} --endpoint https://${ENDPOINT}"
else
    echo "✓ 使用ossutil配置文件中的密钥"
    echo "提示: 如需使用环境变量，请设置 OSS_ACCESS_KEY_ID 和 OSS_ACCESS_KEY_SECRET"
fi

# 上传DMG文件
DMG_NAME="LimeReader_vPROJECT_VERSION_PLACEHOLDER_macOS.dmg"
DMG_LOCAL_PATH="${UPLOAD_DIR}/${DMG_NAME}"

if [ -f "$DMG_LOCAL_PATH" ]; then
    echo ""
    echo "上传DMG文件..."
    echo "  上传: ${DMG_NAME}"
    DMG_OSS_PATH="oss://${BUCKET}/${OSS_PREFIX}/${DMG_NAME}"
    
    if [ -n "$AUTH_PARAMS" ]; then
        ossutil cp "$DMG_LOCAL_PATH" "$DMG_OSS_PATH" $AUTH_PARAMS
    else
        ossutil cp "$DMG_LOCAL_PATH" "$DMG_OSS_PATH"
    fi
    
    if [ $? -eq 0 ]; then
        echo "  ✓ 上传成功"
    else
        echo "  ❌ 上传失败"
        exit 1
    fi
fi

# 上传version.json
echo ""
echo "上传version.json..."
VERSION_LOCAL_PATH="${UPLOAD_DIR}/version.json"
VERSION_OSS_PATH="oss://${BUCKET}/${OSS_PREFIX}/version.json"

if [ -n "$AUTH_PARAMS" ]; then
    ossutil cp "$VERSION_LOCAL_PATH" "$VERSION_OSS_PATH" $AUTH_PARAMS
else
    ossutil cp "$VERSION_LOCAL_PATH" "$VERSION_OSS_PATH"
fi

if [ $? -eq 0 ]; then
    echo "✓ version.json上传成功"
else
    echo "❌ version.json上传失败"
    exit 1
fi

echo ""
echo "=========================================="
echo "  上传完成！"
echo "=========================================="
echo ""
echo "验证链接:"
echo "  version.json:"
echo "    OSS_BASE_URL_PLACEHOLDER/${OSS_PREFIX}/version.json"

if [ -f "$DMG_LOCAL_PATH" ]; then
    echo ""
    echo "  DMG文件:"
    echo "    OSS_BASE_URL_PLACEHOLDER/${OSS_PREFIX}/${DMG_NAME}"
fi

echo ""
echo "验证命令:"
echo "  curl -s OSS_BASE_URL_PLACEHOLDER/${OSS_PREFIX}/version.json"
echo ""
UPLOAD_SCRIPT_EOF

# 替换占位符
sed -i.bak "s/PROJECT_VERSION_PLACEHOLDER/${PROJECT_VERSION}/g" "$UPLOAD_SCRIPT_PATH"
sed -i.bak "s|OSS_BASE_URL_PLACEHOLDER|${OSS_BASE_URL}|g" "$UPLOAD_SCRIPT_PATH"
rm -f "${UPLOAD_SCRIPT_PATH}.bak"

chmod +x "$UPLOAD_SCRIPT_PATH"

echo "[SUCCESS] 上传脚本已生成"

# 显示摘要
echo ""
echo "========================================"
echo " 部署完成"
echo "========================================"
echo ""
echo "[SUCCESS] 构建成功"
echo ""
echo "生成的文件:"
echo "  • DMG安装包: ${UPLOAD_DIR}/${DMG_NAME} (${DMG_SIZE_MB} MB)"
echo "  • version.json: ${UPLOAD_DIR}/version.json"
echo "  • 上传脚本: ${UPLOAD_DIR}/upload_to_oss.sh"
echo ""
echo "下一步:"
echo "  1. 测试应用: open ${DIST_APP_PATH}"
echo "  2. 测试DMG: open ${DMG_UPLOAD_PATH}"
echo "  3. 上传OSS: bash ${UPLOAD_DIR}/upload_to_oss.sh"
echo "  4. 验证: curl ${OSS_BASE_URL}/${OSS_PREFIX}/version.json"
echo ""

# 返回原始目录
cd "$SCRIPT_DIR"

# 自动上传到OSS（如果指定了 -u 参数）
if [ "$AUTO_UPLOAD" = true ]; then
    echo ""
    echo "========================================"
    echo " 开始上传到OSS"
    echo "========================================"
    echo ""
    
    if [ -f "$UPLOAD_SCRIPT_PATH" ]; then
        bash "$UPLOAD_SCRIPT_PATH"
        
        if [ $? -eq 0 ]; then
            echo ""
            echo "[SUCCESS] 上传完成"
        else
            echo ""
            echo "[ERROR] 上传失败"
        fi
    else
        echo "[ERROR] 找不到上传脚本: $UPLOAD_SCRIPT_PATH"
    fi
    echo ""
fi

echo "脚本执行完成！"

